<template>
  <div class="dashboard-container">
    <el-card class="page-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <el-icon class="header-icon"><DataAnalysis /></el-icon>
            <span class="header-title">数据可视化</span>
          </div>
          <div class="header-right">
            <el-date-picker
              v-model="filterMonth"
              type="month"
              placeholder="选择月份"
              format="YYYY-MM"
              value-format="YYYY-MM"
              size="large"
              @change="loadDashboardData"
            />
          </div>
        </div>
      </template>
      
      <!-- 统计卡片 -->
      <div class="statistics-cards">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-card class="stat-card" shadow="hover">
              <div class="stat-content">
                <div class="stat-icon" style="background: #409eff;">
                  <el-icon><Clock /></el-icon>
                </div>
                <div class="stat-info">
                  <div class="stat-label">总打卡次数</div>
                  <div class="stat-value">{{ dashboardData.totalCheckIns || 0 }}</div>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-card" shadow="hover">
              <div class="stat-content">
                <div class="stat-icon" style="background: #67c23a;">
                  <el-icon><User /></el-icon>
                </div>
                <div class="stat-info">
                  <div class="stat-label">正常出勤人数</div>
                  <div class="stat-value">{{ dashboardData.normalAttendance || 0 }}</div>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-card" shadow="hover">
              <div class="stat-content">
                <div class="stat-icon" style="background: #e6a23c;">
                  <el-icon><Document /></el-icon>
                </div>
                <div class="stat-info">
                  <div class="stat-label">请假人数</div>
                  <div class="stat-value">{{ dashboardData.leaveCount || 0 }}</div>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-card" shadow="hover">
              <div class="stat-content">
                <div class="stat-icon" style="background: #f56c6c;">
                  <el-icon><Timer /></el-icon>
                </div>
                <div class="stat-info">
                  <div class="stat-label">加班人次</div>
                  <div class="stat-value">{{ dashboardData.overtimeCount || 0 }}</div>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
      
      <el-divider />
      
      <!-- 图表区域 -->
      <div class="charts-section">
        <el-row :gutter="20">
          <!-- 考勤趋势图 -->
          <el-col :span="12">
            <el-card class="chart-card" shadow="hover">
              <template #header>
                <div class="chart-header">考勤趋势</div>
              </template>
              <div ref="attendanceTrendChart" class="chart-container"></div>
            </el-card>
          </el-col>
          
          <!-- 异常类型分布 -->
          <el-col :span="12">
            <el-card class="chart-card" shadow="hover">
              <template #header>
                <div class="chart-header">异常类型分布</div>
              </template>
              <div ref="exceptionTypeChart" class="chart-container"></div>
            </el-card>
          </el-col>
        </el-row>
        
        <el-row :gutter="20" style="margin-top: 20px;">
          <!-- 请假类型分布 -->
          <el-col :span="12">
            <el-card class="chart-card" shadow="hover">
              <template #header>
                <div class="chart-header">请假类型分布</div>
              </template>
              <div ref="leaveTypeChart" class="chart-container"></div>
            </el-card>
          </el-col>
          
          <!-- 出勤率统计 -->
          <el-col :span="12">
            <el-card class="chart-card" shadow="hover">
              <template #header>
                <div class="chart-header">出勤率统计</div>
              </template>
              <div ref="attendanceRateChart" class="chart-container"></div>
            </el-card>
          </el-col>
        </el-row>
      </div>
    </el-card>
  </div>
</template>

<script>
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import * as echarts from 'echarts'
import request from '../utils/request'
import { ElMessage } from 'element-plus'
import { DataAnalysis, Clock, User, Document, Timer } from '@element-plus/icons-vue'

export default {
  name: 'Dashboard',
  components: {
    DataAnalysis,
    Clock,
    User,
    Document,
    Timer
  },
  setup() {
    const filterMonth = ref('')
    const dashboardData = ref({
      totalCheckIns: 0,
      normalAttendance: 0,
      leaveCount: 0,
      overtimeCount: 0
    })
    
    const attendanceTrendChart = ref(null)
    const exceptionTypeChart = ref(null)
    const leaveTypeChart = ref(null)
    const attendanceRateChart = ref(null)
    
    let attendanceTrendChartInstance = null
    let exceptionTypeChartInstance = null
    let leaveTypeChartInstance = null
    let attendanceRateChartInstance = null
    
    // 初始化月份为当前月份
    const initMonth = () => {
      const now = new Date()
      filterMonth.value = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`
    }
    
    // 加载仪表盘数据
    const loadDashboardData = async () => {
      try {
        const res = await request.get('/attendance/dashboard/data', {
          params: {
            month: filterMonth.value
          }
        })
        if (res.code === 200 && res.data) {
          dashboardData.value = res.data.statistics || dashboardData.value
          // 渲染图表
          await nextTick()
          renderCharts(res.data)
        }
      } catch (error) {
        console.error('加载数据失败', error)
        ElMessage.warning('加载数据失败，显示模拟数据')
        // 使用模拟数据
        const mockData = {
          statistics: {
            totalCheckIns: 156,
            normalAttendance: 142,
            leaveCount: 8,
            overtimeCount: 12
          },
          attendanceTrend: [
            { date: '2024-01-01', checkIns: 45 },
            { date: '2024-01-02', checkIns: 48 },
            { date: '2024-01-03', checkIns: 42 },
            { date: '2024-01-04', checkIns: 50 },
            { date: '2024-01-05', checkIns: 46 }
          ],
          exceptionType: [
            { name: '迟到', value: 15 },
            { name: '早退', value: 8 },
            { name: '缺勤', value: 5 }
          ],
          leaveType: [
            { name: '年假', value: 20 },
            { name: '病假', value: 12 },
            { name: '事假', value: 8 },
            { name: '调休', value: 5 }
          ],
          attendanceRate: [
            { name: '90%以上', value: 120 },
            { name: '80-90%', value: 15 },
            { name: '70-80%', value: 5 },
            { name: '70%以下', value: 2 }
          ]
        }
        dashboardData.value = mockData.statistics
        await nextTick()
        renderCharts(mockData)
      }
    }
    
    // 渲染考勤趋势图
    const renderAttendanceTrendChart = (data) => {
      if (!attendanceTrendChart.value) return
      
      if (!attendanceTrendChartInstance) {
        attendanceTrendChartInstance = echarts.init(attendanceTrendChart.value)
      }
      
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: data.map(item => item.date)
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '打卡次数',
            type: 'line',
            smooth: true,
            data: data.map(item => item.checkIns),
            areaStyle: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [
                  { offset: 0, color: 'rgba(64, 158, 255, 0.3)' },
                  { offset: 1, color: 'rgba(64, 158, 255, 0.1)' }
                ]
              }
            },
            itemStyle: {
              color: '#409eff'
            }
          }
        ]
      }
      
      attendanceTrendChartInstance.setOption(option)
    }
    
    // 渲染异常类型分布图
    const renderExceptionTypeChart = (data) => {
      if (!exceptionTypeChart.value) return
      
      if (!exceptionTypeChartInstance) {
        exceptionTypeChartInstance = echarts.init(exceptionTypeChart.value)
      }
      
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left'
        },
        series: [
          {
            name: '异常类型',
            type: 'pie',
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: true,
              formatter: '{b}: {c}\n({d}%)'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '16',
                fontWeight: 'bold'
              }
            },
            data: data
          }
        ]
      }
      
      exceptionTypeChartInstance.setOption(option)
    }
    
    // 渲染请假类型分布图
    const renderLeaveTypeChart = (data) => {
      if (!leaveTypeChart.value) return
      
      if (!leaveTypeChartInstance) {
        leaveTypeChartInstance = echarts.init(leaveTypeChart.value)
      }
      
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left'
        },
        series: [
          {
            name: '请假类型',
            type: 'pie',
            radius: '60%',
            data: data,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      }
      
      leaveTypeChartInstance.setOption(option)
    }
    
    // 渲染出勤率统计图
    const renderAttendanceRateChart = (data) => {
      if (!attendanceRateChart.value) return
      
      if (!attendanceRateChartInstance) {
        attendanceRateChartInstance = echarts.init(attendanceRateChart.value)
      }
      
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: data.map(item => item.name)
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '人数',
            type: 'bar',
            data: data.map(item => item.value),
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#83bff6' },
                { offset: 0.5, color: '#188df0' },
                { offset: 1, color: '#188df0' }
              ])
            },
            emphasis: {
              itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: '#2378f7' },
                  { offset: 0.7, color: '#2378f7' },
                  { offset: 1, color: '#83bff6' }
                ])
              }
            }
          }
        ]
      }
      
      attendanceRateChartInstance.setOption(option)
    }
    
    // 渲染所有图表
    const renderCharts = (data) => {
      renderAttendanceTrendChart(data.attendanceTrend || [])
      renderExceptionTypeChart(data.exceptionType || [])
      renderLeaveTypeChart(data.leaveType || [])
      renderAttendanceRateChart(data.attendanceRate || [])
    }
    
    // 窗口大小改变时重新调整图表
    const handleResize = () => {
      attendanceTrendChartInstance?.resize()
      exceptionTypeChartInstance?.resize()
      leaveTypeChartInstance?.resize()
      attendanceRateChartInstance?.resize()
    }
    
    onMounted(() => {
      initMonth()
      loadDashboardData()
      window.addEventListener('resize', handleResize)
    })
    
    onUnmounted(() => {
      window.removeEventListener('resize', handleResize)
      attendanceTrendChartInstance?.dispose()
      exceptionTypeChartInstance?.dispose()
      leaveTypeChartInstance?.dispose()
      attendanceRateChartInstance?.dispose()
    })
    
    return {
      filterMonth,
      dashboardData,
      attendanceTrendChart,
      exceptionTypeChart,
      leaveTypeChart,
      attendanceRateChart,
      loadDashboardData
    }
  }
}
</script>

<style scoped>
.dashboard-container {
  width: 100%;
  height: 100%;
}

.page-card {
  border-radius: 12px;
  border: none;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.header-icon {
  font-size: 24px;
  color: #409eff;
}

.header-title {
  font-size: 20px;
  font-weight: 600;
  color: #1a1a1a;
}

.statistics-cards {
  margin-bottom: 24px;
}

.stat-card {
  border-radius: 8px;
  transition: all 0.3s;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.stat-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 28px;
}

.stat-info {
  flex: 1;
}

.stat-label {
  font-size: 14px;
  color: #909399;
  margin-bottom: 8px;
}

.stat-value {
  font-size: 28px;
  font-weight: 600;
  color: #303133;
}

.charts-section {
  margin-top: 24px;
}

.chart-card {
  border-radius: 8px;
}

.chart-header {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.chart-container {
  width: 100%;
  height: 350px;
}
</style>

